package com.itcast.cheetah.crr.mq;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.itcast.cheetah.crr.product.entity.ProductInfo;
import com.itcast.cheetah.crr.product.model.ProductInfoDetail;
import com.itcast.cheetah.crr.product.service.impl.ProductInfoServiceImpl;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * @className: MQReciever
 * @description: 接收者
 * @author: cheetah
 * @date: 2023/3/10 10:40
 * @Version: 1.0
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class MQReciever {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String REDIS_PRODUCT_KEY = "product:info:";

    @RabbitListener(queues = "canal_queue")//监听队列名称
    public void getMsg(Message message, Channel channel, String msg) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("消费的队列消息来自：" + message.getMessageProperties().getConsumerQueue());

            //删除reids中对应的key
            ProductInfoDetail productInfoDetail = JSON.parseObject(msg, ProductInfoDetail.class);
            log.info("库名："+ productInfoDetail.getDatabase());
            log.info("表名: "+ productInfoDetail.getTable());
            if(productInfoDetail!=null && productInfoDetail.getData()!=null){
                List<ProductInfo> data = productInfoDetail.getData();
                ProductInfo productInfo = data.get(0);
                if(productInfo!=null){
                    Long id = productInfo.getId();
                    redisTemplate.delete(REDIS_PRODUCT_KEY+id);
                    channel.basicAck(deliveryTag, true);
                    return;
                }
            }
            channel.basicReject(deliveryTag ,true);
            return;
        }catch (Exception e){
            channel.basicReject(deliveryTag,false);
            e.printStackTrace();
        }
    }
}
